package com.huanwei.cc.base;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.gyf.barlibrary.ImmersionBar;

import butterknife.ButterKnife;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public abstract class BaseActivity extends AppCompatActivity {

    protected Context context;

    private CompositeSubscription mCompositeSubscription;
    protected ImmersionBar mImmersionBar;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(setLayoutId());
        //绑定控件
        ButterKnife.bind(this);

        context = this;
        //初始化沉浸式
        if (isImmersionBarEnabled())
            initImmersionBar();
        initViewsAndEvents();
    }

    public abstract int setLayoutId();


    public abstract void initViewsAndEvents();

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();
    }

    @Override
    protected void onDestroy() {
        onUnsubscribe();
        super.onDestroy();
        if (mImmersionBar != null)
            mImmersionBar.destroy();  //在BaseActivity里销毁
    }

//
//    public <T> void getHttp(RxSubscribe<T> subscriber, String url, Map<String, String> map) {
//        Observable observable = apiService.executeGet(url, map)
//                .map(new HttpResultFunc());
//        toSubscribe(observable, subscriber);
//    }


//    public <T> void postHttp(RxSubscribe<T> subscriber, String url, Map<String, String> map) {
//        Observable observable = apiService.executePost(url, map)
//                .map(new HttpResultFunc());
//        toSubscribe(observable, subscriber);
//    }

    private <T> void toSubscribe(Observable<T> o, Subscriber<T> s) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s));
    }

    public void onUnsubscribe() {
        //取消注册，以避免内存泄露
        if (mCompositeSubscription != null && mCompositeSubscription
                .hasSubscriptions())
            mCompositeSubscription.unsubscribe();
    }


}
